/**
 * 文件名：@LogInterceptor.java <br/>
 * 包名：cn.efunbox.afw.web.mvc.interceptor <br/>
 * 项目名：afw-web <br/>
 * @author xtwin <br/>
 */
package cn.efunbox.afw.web.mvc.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.efunbox.afw.web.util.WebUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 类名：LogInterceptor  <br />
 *
 * 功能：日志打印拦截器
 *
 * @author xtwin <br />
 * 创建时间：2015年12月9日 下午3:26:08  <br />
 * @version 2015年12月9日
 */
public class LogInterceptor extends HandlerInterceptorAdapter {
	
	// 日志记录器
	private static final Log logger = LogFactory.getLog(LogInterceptor.class);

	/**
	 * 功能: <br/>
	 * 
	 * 重写：xtwin <br/>
	 * 
	 * @version ：2015年12月9日 下午3:26:22<br/>
	 * 
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception <br/>
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("header print is start....");
			Enumeration<String> headerNames = request.getHeaderNames();
			
			while (headerNames.hasMoreElements()) {
				String name = headerNames.nextElement();
				
				logger.debug("header is : [" + name + " = " + request.getHeader(name) + "]");
			}
			
			logger.debug("header print is end....");
			
			// 打印请求信息
			logger.debug("request method is : " + request.getMethod() + "");
			logger.debug("request uri is : " + request.getRequestURI());
			logger.debug("request query string is : " + request.getQueryString());
		}
		
		// 解析ip，并将ip放到MDC中，用于日志打印
		MDC.put("ip", WebUtil.resolveHost(request));
		
		return super.preHandle(request, response, handler);
	}

}
